import React, { Fragment, memo, useState } from 'react';
import { useDispatch } from 'react-redux';

import TodoItem from './Todoitem';
import { List } from 'antd';

import { getEditAction } from '../store/actionCreators';

export default memo(function DataList({ list }) {
  // redux hooks
  const dispatch = useDispatch();

  // orter hooks
  const [dragging, setDragging] = useState(false); // 是否移动
  const [draggingIndex, setDraggingIndex] = useState(-1); // 当前移动的下标
  const [startPageY, setStartPageY] = useState(0); // y轴起始位置
  const [offsetPageY, setOffsetPageY] = useState(0); // y轴偏移位置

  const lineHeight = 64;

  const maskStyle = {
    position: 'fixed',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgorund: 'rgba(0,0,0,0.5)'
  };

  // 点击的时候记录 Y 轴的位置
  const setDraggingClick = (e, index) => {
    if (e.target.nodeName === 'svg') {
      setDragging(true);
      setStartPageY(e.pageY);
      setDraggingIndex(index);
    }
  };

  // 松开鼠标的时候，从新初始化 startPageY、draggingIndex,
  const onMouseUp = (e) => {
    setDragging(false);
    setStartPageY(0);
    setDraggingIndex(-1);
  };

  // 从新计算数组
  const move = (arr = [], startIndex, toIndex) => {
    arr = arr.slice();
    arr.splice(toIndex, 0, arr.splice(startIndex, 1)[0]);
    return arr;
  };

  // 移动动画
  const getDraggingStyle = (index) => {
    if (index !== draggingIndex) return;
    return {
      backgorundColor: '#ccc',
      transform: `translate(10px,${offsetPageY}px)`,
      opacity: 0.5
    };
  };

  // 移动的轨迹
  const onMouseMove = (e) => {
    let offset = e.pageY - startPageY;
    if (offset > lineHeight && draggingIndex < list.length - 1) {
      //  向下移动
      offset -= lineHeight;
      // move 期间，state 的数据是动态变化的，draggingIndex 始终比上一个多 1
      // console.log(move(list, draggingIndex, draggingIndex + 1));
      dispatch(getEditAction(move(list, draggingIndex, draggingIndex + 1)));
      setDraggingIndex(draggingIndex + 1);
      setStartPageY(startPageY + lineHeight);
    } else if (offset < -lineHeight && draggingIndex > 0) {
      // 向上移动
      offset += lineHeight;
      dispatch(getEditAction(move(list, draggingIndex, draggingIndex - 1)));
      setDraggingIndex(draggingIndex - 1);
      setStartPageY(startPageY - lineHeight);
    }
    // item 移动的距离
    setOffsetPageY(offset);
  };

  return (
    <Fragment>
      <List
        bordered
        dataSource={list}
        renderItem={(item, index) => (
          <List.Item
            id="listItem"
            key={item.id}
            onMouseDown={(e) => setDraggingClick(e, index)}
            style={getDraggingStyle(index)}
          >
            <TodoItem {...item} />
          </List.Item>
        )}
      />

      {/* 用一个遮罩监听事件，也可以监听整个 document */}
      {dragging && (
        <div
          style={maskStyle}
          onMouseUp={(e) => onMouseUp(e)}
          onMouseMove={(e) => onMouseMove(e)}
        ></div>
      )}
    </Fragment>
  );
});
